require 'librmpd'
require "#{RAILS_ROOT}/lib/mpd_extras.rb"

module Mpd
  class Radio
    cattr_reader :connection
    MPD.send(:include, Mpd::Extras) #Voor die andere, anders neemt 'ie de instance methods niet over
  
    def connection
      if @@connection.nil?
        @@connection = MPD.new(config[:host], config[:port])
        @@connection.connect
      elsif @@connection.connected? == false
        @@connection.connect
      end
      
      @@connection
    end
  
    def config
      config = YAML.load_file("#{RAILS_ROOT}/config/mpd.yml")[RAILS_ENV]
      { :host => config['host'] || 'localhost',
        :port => config['port'] || 6600,
        :password => config['password']
      }
    end
  
    def self.call_on_mpd(*args)
      return_methods = []
      exceptions = []
      
      return false if args.empty?
      
      if args.last.class == Hash && args.last[:except]
        exceptions = args.last[:except]
        args.pop
      end
      exceptions.push('playlists') #Deze overschrijven we, want die gaat de eerste keer fout
        
      #Collect all methods that're going to be inherrited
      existing_instance_methods = Mpd::Extras.instance_methods(false).concat(MPD.instance_methods(false))
      
      #If the first argument is :all, do all the methods
      if (args.first == :all)
        methods = existing_instance_methods
      else
        methods = args
      end
      
      #Remove the exceptions
      methods -= exceptions.to_a
    
      methods.each do |method|
          
        next if !existing_instance_methods.include?(method)
      
        #meta_eval do
        class_eval do
          define_method method  do |*args|
            self.connection.send method, *args
          end
        end
          
        return_methods << method
      end
      
      return return_methods
    end
    
    call_on_mpd :all
  
  end #class Radio
end #module Mpd